package com.jmda.platform.repository.form.action;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmda.platform.commom.SequenceService;
import com.jmda.platform.engine.mybatis.MybatisEngine;
import com.jmda.platform.repository.ResositoryException;
import com.jmda.platform.repository.RespositoryConstant;
import com.jmda.platform.repository.form.model.FormMetadataButtonModel;
import com.jmda.platform.repository.form.model.FormMetadataModel;
import com.jmda.platform.repository.form.model.FormModel;
import com.jmda.platform.repository.form.service.FormMetadataMapService;
import com.jmda.platform.repository.form.service.FormMetadataService;
import com.jmda.platform.repository.form.service.FormService;
import com.jmda.platform.repository.form.util.FormMetadateButtonCommonMethod;
import com.jmda.platform.repository.metadata.service.MetadataService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/repository/form/buttons")
public class FormMetadataButtonsController {
	@Resource
	FormMetadataService formMetadataService;
	@Resource
	FormService formService;
	@Resource
	FormMetadataMapService formMetadataMapService;
	@Resource
	MetadataService metadataService;
	@Resource
	SequenceService seq;
	@Resource
	MybatisEngine mybatis;
	@Resource
	FormMetadateButtonCommonMethod formMetadateButtonCommonMethod;
	@RequestMapping(value = "/openFormMeatadataButtonsPage", method = { RequestMethod.POST, RequestMethod.GET })
	public String openFormMeatadataPage(String form_id, String formMetadataId, ModelMap map) throws ResositoryException {
		FormMetadataModel formMetadataModel = formMetadataService.getFormMetadataModel(form_id, formMetadataId);
		map.put("form_id", form_id);
		map.put("formMetadataName", formMetadataModel.getName());
		map.put("formMetadataId", formMetadataModel.getId());
		if(formMetadataModel.getType() == RespositoryConstant.SYS_FORM_METADATA_TYPE_MASTER){
			map.put("is_master_dataset", "true");
		}else{
			map.put("is_master_dataset", "false");
		}
		return "repository/form/Sys_Repository_Form_Metadata_Buttons";
	}

	@SuppressWarnings({ "unchecked" })
	@RequestMapping(value = "/getFormMeatadataButtonsJson", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String getFormMeatadataButtonsJson(String form_id, String formMetadataId) throws JsonProcessingException, ResositoryException {
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> json = new HashMap<String, Object>();
		List<FormMetadataButtonModel> list = formMetadataMapService.getFormMetadataButtonList(form_id, formMetadataId);
		list = list == null ? new ArrayList<FormMetadataButtonModel>() : list;
		if(list!=null){
			 Collections.sort(list, new Comparator(){   
				@Override
				public int compare(Object o1, Object o2) {
				       if(((FormMetadataButtonModel)o1).getOrderIndex() > ((FormMetadataButtonModel)o2).getOrderIndex()){   

		                    return 1;   
		                }   
		                if(((FormMetadataButtonModel)o1).getOrderIndex() == ((FormMetadataButtonModel)o2).getOrderIndex()){   
		                    return 0;   
		               }   
		               return -1;   
				}
	         }); 
			}
		json.put("root", list);
		json.put("total", list == null ? 0 : list.size());
		return mapper.writeValueAsString(json);
	}

	@RequestMapping(value = "/saveFormMetadataButton", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String saveFormMetadataButton(String form_id, String formMetadataId, String datas) throws ResositoryException, IOException {
		ObjectMapper mapper = new ObjectMapper();	
		List<FormMetadataButtonModel> modifyMetadataButtonList = mapper.readValue(datas, new TypeReference<ArrayList<FormMetadataButtonModel>>() {
		});
		if (modifyMetadataButtonList != null && modifyMetadataButtonList.size() > 0) {
			FormModel formModel = formService.get(form_id);
			List<FormMetadataModel> formMetadataModellist = formModel.getFormMetadataList();
			for (FormMetadataModel formMetadataModel : formMetadataModellist) {
				// 找到对应的数据集
				if (formMetadataModel.getId().equals(formMetadataId)) {
					List<FormMetadataButtonModel> formMetadataButtonList = formMetadataModel.getFormMetadataButtonList();
					formMetadataButtonList=formMetadataButtonList==null?new ArrayList<FormMetadataButtonModel>():formMetadataButtonList;
					for (FormMetadataButtonModel newButtonModel : modifyMetadataButtonList) {
						if (newButtonModel.getId() == null || newButtonModel.getId().trim().length() == 0) {
							newButtonModel.setId(seq.getUUID());
							newButtonModel.setOrderIndex(formService.getFormMetadataButtonNextIndex(formMetadataModel));
							formMetadataButtonList.add(newButtonModel);
						}
					}
					//修改的按钮
					for (FormMetadataButtonModel button : formMetadataButtonList) {
						for (FormMetadataButtonModel newButtonModel : modifyMetadataButtonList) {
							if (button.getId().equals(newButtonModel.getId())) {
								button.setHandler(newButtonModel.getHandler());
								button.setIconCls(newButtonModel.getIconCls());
								button.setTitle(newButtonModel.getTitle());
								//button.setTooltip(newButtonModel.getTooltip());
								button.setIconClsChild(newButtonModel.getIconClsChild());
								button.setCustomHtml(newButtonModel.getCustomHtml());
							}
						}
					}
					formMetadataModel.setFormMetadataButtonList(formMetadataButtonList);
					formService.store(formModel);
					break;
				}
			}
		}
		return "ok";
	}

	@RequestMapping(value = "/removeFormMetadataButton", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String removeFormMetadataButton(String form_id, String formMetadataId, String ids) throws ResositoryException, IOException {
		String[] idArray = ids.split(",");
		if (idArray != null && idArray.length > 0) {
			FormModel formModel = formService.get(form_id);
			List<FormMetadataModel> formMetadataModellist = formModel.getFormMetadataList();
			for (FormMetadataModel formMetadataModel : formMetadataModellist) {
				// 找到对应的数据集
				if (formMetadataModel.getId().equals(formMetadataId)) {
					List<FormMetadataButtonModel> formMetadataButtonList = formMetadataModel.getFormMetadataButtonList();
					List<FormMetadataButtonModel> newFormMetadataButtonList = new ArrayList<FormMetadataButtonModel>();
					for (FormMetadataButtonModel formMetadataButtonModel : formMetadataButtonList) {
						boolean isOK = true;
						// 匹配到删除的列
						for (int i = 0; i < idArray.length; i++) {
							if (formMetadataButtonModel.getId().equals(idArray[i])) {
								isOK = false;
								break;
							}
						}
						if (isOK) {
							newFormMetadataButtonList.add(formMetadataButtonModel);
						}
					}
					formMetadataModel.setFormMetadataButtonList(newFormMetadataButtonList);
					formService.store(formModel);
					break;
				}
			}
		}
		return "ok";
	}
	@RequestMapping(value = "/sortGird", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String sortGirdMap( String sourceId,  String targetId,String form_id,String form_er_id) {
		return formMetadateButtonCommonMethod.formMetadataButtonModelOrder(form_id,form_er_id,sourceId, targetId);
	}
}
